package com.lv.suyiyong.hfr.ui

import android.graphics.Color
import android.graphics.Typeface
import android.view.LayoutInflater
import android.view.View
import android.widget.TextView
import androidx.fragment.app.Fragment
import androidx.lifecycle.lifecycleScope
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.SizeUtils
import com.google.android.material.tabs.TabLayoutMediator
import com.lv.common.adapter.FactoryContainerPagerAdapter
import com.lv.common.base.BaseActivity
import com.lv.common.bean.CommonSelectedBean
import com.lv.common.ktx.AppBarState
import com.lv.common.ktx.LoadSrc
import com.lv.common.ktx.initSingleClickListener
import com.lv.common.ktx.setSelectedTabIndicatorFixWidth
import com.lv.common.ktx.setViewFlipper
import com.lv.common.ktx.setupAppBarLayoutListener
import com.lv.common.ktx.viewLifeCycleOwner
import com.lv.common.network.model.DataResult
import com.lv.common.utils.ARoutUtils
import com.lv.common.utils.MoneyUtil
import com.lv.common.utils.StatusBarUtil
import com.lv.common.utils.showToast
import com.lv.service.bean.FindProsBean
import com.lv.service.bean.GoodsItemBean
import com.lv.service.bean.SpecialOfferTopBean
import com.lv.service.model.ServiceViewModel
import com.lv.service.network.BaseYgxRsp
import com.lv.service.network.onBizError
import com.lv.service.network.onBizOK
import com.lv.service.network.onFailure
import com.lv.service.network.onSuccess
import com.lv.service.repo.UserDbHelper
import com.lv.service.repo.UserInfo
import com.lv.service.room.category.CategoryBean
import com.lv.service.room.category.CategoryDbHelper
import com.lv.service.utils.YgxToolsKt
import com.lv.suyiyong.hfr.R
import com.lv.suyiyong.hfr.adapter.BannerCouponAdapter
import com.lv.suyiyong.hfr.adapter.DynamicCircleImagesAdapter
import com.lv.suyiyong.hfr.databinding.ActivityCouponActionTabBinding
import com.lv.suyiyong.hfr.fragment.CouponFactoryTabFragment
import com.youth.banner.listener.OnBannerListener
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.async
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import org.koin.androidx.viewmodel.ext.android.viewModel

/**
 * 作者： ygx
 * 创建日期：2023/3/28 5:51 PM
 * 签名： 天行健，君子以自强不息；地势坤，君子以厚德载物。
 * -    _              _           _     _   ____  _             _ _
 * -   / \   _ __   __| |_ __ ___ (_) __| | / ___|| |_ _   _  __| (_) ___
 * -  / _ \ | '_ \ / _` | '__/ _ \| |/ _` | \___ \| __| | | |/ _` | |/ _ \
 * - / ___ \| | | | (_| | | | (_) | | (_| |  ___) | |_| |_| | (_| | | (_) |
 * -/_/   \_\_| |_|\__,_|_|  \___/|_|\__,_| |____/ \__|\__,_|\__,_|_|\___/
 * <p>
 * You never know what you can do until you try !
 * ----------------------------------------------------------------
 * 描述：特惠活动 页面
 */
@Route(path = ARoutUtils.CouponActionTabActivity)
class CouponActionTabActivity : BaseActivity<ActivityCouponActionTabBinding>(),
    View.OnClickListener {
    private val mBannerTopData = mutableListOf<List<GoodsItemBean>>()
    private val mBannerLeftData = mutableListOf<List<GoodsItemBean>>()
    private val mBannerRightData = mutableListOf<List<GoodsItemBean>>()
    private val mPics = mutableListOf<String>()
    private var mBannerTopAdapter: BannerCouponAdapter? = null
    private var mBannerLeftAdapter: BannerCouponAdapter? = null
    private var mBannerRightAdapter: BannerCouponAdapter? = null
    private var mPicAdapter: DynamicCircleImagesAdapter? = null
    private var mScrollY = 0
    private val mTopUrl =
        "https://suyiyong.oss-cn-hangzhou.aliyuncs.com/iOS/projectPic/hfr/specilaDiscountNav.png"
    private val mTopIv =
        "https://suyiyong.oss-cn-hangzhou.aliyuncs.com/1231/hengfuran/thhd1.png?x-oss-process=image/format,webp"
    private var mUserInfo: UserInfo? = null
    private val mTabs = mutableListOf<CommonSelectedBean>()
    private var mAdapter: FactoryContainerPagerAdapter? = null

    private val serviceViewModel: ServiceViewModel by viewModel()
    private val myScope: CoroutineScope = CoroutineScope(SupervisorJob())
    override fun getLayoutRes() = R.layout.activity_coupon_action_tab
    override fun initView() {
        super.initView()
        initStatusBar(this, true, false)
        mBinding.apply {
            StatusBarUtil.setHeightAndPadding(this@CouponActionTabActivity, viewStatus)
            ivBackPage.setOnClickListener { finish() }
            initSingleClickListener(viewSearch)
        }
    }


    override fun initConfig() {
        super.initConfig()
        mBinding.ivTitlePage.LoadSrc(mTopUrl)
        mBinding.ivTop.LoadSrc(mTopIv)
        initBannerAdapter()
        bannerObserver()
        lifecycleScope.launch {
            val taskCategory = async {
                val mAllCategory = getCategoryForDB()
                mTabs.clear()
                mTabs.add(CommonSelectedBean("推荐", postiont = 0, selected = true))
                mAllCategory?.forEach {
                    mTabs.add(CommonSelectedBean(it.name, postiont = it.fcaid ?: 0))
                }
            }
            taskCategory.await()
            initPage()
        }

        UserDbHelper.getLiveUserInfo(this).observeKt {
            mUserInfo = it
        }
    }

    private suspend fun getCategoryForDB(): List<CategoryBean>? {
        return withContext(Dispatchers.IO) {
            //获取工厂分类
            CategoryDbHelper.getFindAllCategorySuspend(this@CouponActionTabActivity)
        }
    }

    private fun specialOfferTop() {
        lifecycleScope.launchWhenCreated {
            val result: DataResult<BaseYgxRsp> =
                myScope.async { serviceViewModel.specialOfferTop() }.await()
            parseBannerResult(result)
        }
    }

    private fun parseBannerResult(data: DataResult<BaseYgxRsp>) {
        data.onSuccess {
            onBizOK<SpecialOfferTopBean> { code, data, message, result ->
                mBinding.tvDiscount.text = data?.discount
                val wantnum = data?.wantnum ?: 0
                val num = MoneyUtil.formatMoneyW(wantnum)
                mBinding.tvWant.text = "${num}人想要"
                val lowprice = data?.lowprice
                val chunkedTop = lowprice?.chunked(4)
                mBannerTopData.clear()
                chunkedTop?.let { mBannerTopData.addAll(it) }
                mBannerTopAdapter?.notifyDataSetChanged()
                val direct = data?.direct
                val chunkedLeft = direct?.chunked(2)
                mBannerLeftData.clear()
                chunkedLeft?.let { mBannerLeftData.addAll(it) }
                mBannerLeftAdapter?.notifyDataSetChanged()
                val selected = data?.selected
                val chunkedRight = selected?.chunked(2)
                mBannerRightData.clear()
                chunkedRight?.let { mBannerRightData.addAll(it) }
                mBannerRightAdapter?.notifyDataSetChanged()
                mPics.clear()
                val images = data?.images
                images?.let { mPics.addAll(it) }
                mPicAdapter?.notifyDataSetChanged()
            }
            onBizError<String> { code, message, data ->
                showToast(message)
            }
        }
    }

    /**
     * 设置Banner适配器
     */
    private fun bannerObserver() {
        mBinding.bannerTop.addBannerLifecycleObserver(viewLifeCycleOwner)
            .setAdapter(mBannerTopAdapter)
            .setIntercept(false)
        mBinding.bannerLeft.addBannerLifecycleObserver(viewLifeCycleOwner)
            .setAdapter(mBannerLeftAdapter)
            .setIntercept(false)
        mBinding.bannerRight.addBannerLifecycleObserver(viewLifeCycleOwner)
            .setAdapter(mBannerRightAdapter)
            .setIntercept(false)

    }

    /**
     * 初始化轮播图Adapter
     */
    private fun initBannerAdapter() {
        mBannerTopAdapter = BannerCouponAdapter(mBannerTopData, 0)
        mBannerLeftAdapter = BannerCouponAdapter(mBannerLeftData, 1)
        mBannerRightAdapter = BannerCouponAdapter(mBannerRightData, 1)
        mPicAdapter = DynamicCircleImagesAdapter(mPics)
        mBinding.rvPic.adapter = mPicAdapter
        mBannerTopAdapter?.setOnBannerListener(OnBannerListener<Any?> { data, position ->
//            val indexCommon = mBannerTopData[position]
//            YgxSYYADKt.arout2page(
//                this,
//                indexCommon.tag,
//                indexCommon.url,
//                mUserInfo,
//                adId = if (indexCommon.statistics == 0) indexCommon.id else -1
//            )
//            mBannerTopData[position].statistics = -1
        })
    }


    override fun initEvents() {
        super.initEvents()
        mBinding.appBar.setupAppBarLayoutListener { state ->
            when (state) {
                AppBarState.EXPANDED -> {
                    // 展开状态，比如显示 FAB 或设置标题
                    mBinding.tabLayout.setBackgroundResource(com.lv.common.R.drawable.bg_fff1f1_t_10)
                }

                AppBarState.COLLAPSED -> {
                    // 折叠状态
                    mBinding.tabLayout.setBackgroundResource(com.lv.common.R.drawable.bg_fff1f1)
                }

                AppBarState.PARTIALLY_COLLAPSED -> {
                    // 中间状态
                    mBinding.tabLayout.setBackgroundResource(com.lv.common.R.drawable.bg_fff1f1_t_10)
                }
            }

        }

//        mBinding.appBar.addOnOffsetChangedListener(AppBarLayout.OnOffsetChangedListener { _, verticalOffset ->
//            val abs = abs(verticalOffset)
//            var mAlpha: Float = abs * 1.0f / threshold
//            if (mAlpha < 0) {
//                mAlpha = 0.0f
//            }
//            if (mAlpha > 1) {
//                mAlpha = 1.0f
//            }
//            mBinding.ivTitlePage.alpha = mAlpha
//        })
//        mBinding.appBar.post(Runnable {
//            val layoutParams = mBinding.appBar.layoutParams as CoordinatorLayout.LayoutParams
//            val behavior = layoutParams.behavior as AppBarLayout.Behavior?
//            behavior?.setDragCallback(object : AppBarLayout.Behavior.DragCallback() {
//                override fun canDrag(appBarLayout: AppBarLayout): Boolean {
//                    return true
//                }
//            })
//        })

    }

    override fun initData() {
        super.initData()

    }

    private fun initPage() {
        findPros()
        specialOfferTop()
        initViewPager()
    }

    private fun findPros() {
        val findProsMap = mutableMapOf("hotSearch" to "1")
        lifecycleScope.launchWhenCreated {
            val result: DataResult<BaseYgxRsp> =
                withContext(myScope.coroutineContext) {
                    serviceViewModel.findPros(findProsMap)
                }
            parseFindProsResult(result)
        }
    }

    private fun parseFindProsResult(data: DataResult<BaseYgxRsp>) {
        data.onSuccess {
            onBizOK<FindProsBean> { code, data, message, result ->
                val hotSearch = data?.hotSearch
                hotSearch?.let {
                    setSearchData(hotSearch)
                }
            }
            onBizError<Any> { code, message, data ->

            }
        }
        data.onFailure {

        }
    }

    private fun setSearchData(titles: List<String>) {
        mBinding.marqueeBanner.setViewFlipper(this, titles, 3000) { i ->
            val mLayout: View =
                LayoutInflater.from(this)
                    .inflate(R.layout.item_text_flipper, null)
            val tvTitle = mLayout.findViewById<TextView>(R.id.tv_content)
            //赋值
            tvTitle.text = titles[i]
            tvTitle.setTextColor(Color.parseColor("#ffffff"))
            return@setViewFlipper mLayout
        }
    }


    private fun initViewPager() {

        mAdapter = FactoryContainerPagerAdapter(
            supportFragmentManager, lifecycle,
            mTabs
        )
        mAdapter?.listener = object : FactoryContainerPagerAdapter.CirTabListener {
            override fun getFragment(position: Int): Fragment {
                val fragment = CouponFactoryTabFragment.newInstance(mTabs[position].postiont)
                return fragment
            }
        }

        mBinding.viewpager.adapter = mAdapter
        TabLayoutMediator(mBinding.tabLayout, mBinding.viewpager) { tab, position ->
            tab.text = mTabs[position].name
        }.attach()
        mBinding.viewpager.offscreenPageLimit = mTabs.size
        mBinding.tabLayout.setSelectedTabIndicatorFixWidth(SizeUtils.dp2px(19.0f).toFloat())
        mBinding.tabLayout.addOnTabSelectedListener(YgxToolsKt.setSelectedBoldTab())

        val selecTab = mTabs[0].name ?: ""
        val spannedString = YgxToolsKt.setTextSpan(selecTab, Typeface.BOLD)
        mBinding.tabLayout.getTabAt(0)?.text = spannedString
    }

    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.view_search -> {
                val text =
                    (mBinding.marqueeBanner.currentView?.findViewById<TextView>(R.id.tv_content)?.text
                        ?: "").toString()
                ARouter.getInstance().build(ARoutUtils.CommonSearchActivity)
                    .withString("search", text).withString("searchCode", "1").navigation()
            }
        }
    }


}